/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mailclient;

import Util.EmailTools;
import controller.GoiNhanMail;
import dao.ThongTinKeyDAO;
import dao.ThongTinTaiKhoanMailDAO;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Vector;
import javax.mail.Message;
import javax.mail.internet.InternetAddress;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import pojo.ThongTinTaiKhoanMail;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.activation.DataHandler;
import javax.crypto.Cipher;
import javax.mail.Message.RecipientType;
import javax.mail.*;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.TableColumn;
import pojo.ThongTinKey;

/**
 *
 * @author Hoan My
 */
public class MailManagement extends javax.swing.JFrame {

    private DefaultTableModel tableModel;
    private ThongTinTaiKhoanMail mail = ThongTinTaiKhoanMailDAO.layThongTinTaiKhoanMail();
    private Message[] messages = null;
    private Store store;
    private Folder inbox;

    /**
     * Creates new form MailManagement
     */
    public MailManagement() {
        initComponents();

        btnDownloadAtt.setVisible(false);
        jbtnDeleteMail.setVisible(false);

        this.tableModel = new DefaultTableModel();
        this.tableModel.addColumn("From ");
        this.tableModel.addColumn("Subject ");
        this.tableModel.addColumn("Received Date ");
        this.tableModel.addColumn("Size ");
        this.jtDanhSachEmail.setModel(tableModel);
        TableColumn column = this.jtDanhSachEmail.getColumnModel().getColumn(0);
        column.setPreferredWidth(50);
        column = this.jtDanhSachEmail.getColumnModel().getColumn(1);
        column.setPreferredWidth(150);
        column = this.jtDanhSachEmail.getColumnModel().getColumn(2);
        column.setPreferredWidth(50);
        column = this.jtDanhSachEmail.getColumnModel().getColumn(3);
        column.setPreferredWidth(20);

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane3 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jToolBar1 = new javax.swing.JToolBar();
        btnGetMail = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JToolBar.Separator();
        jButton3 = new javax.swing.JButton();
        btn_ManageKey = new javax.swing.JButton();
        jScrollPane4 = new javax.swing.JScrollPane();
        jtaNoiDungEmail = new javax.swing.JTextArea();
        jScrollPane5 = new javax.swing.JScrollPane();
        jtDanhSachEmail = new javax.swing.JTable();
        jbtnMoreInfo = new javax.swing.JButton();
        jbtnDeleteMail = new javax.swing.JButton();
        btnDownloadAtt = new javax.swing.JButton();
        menuBar = new javax.swing.JMenuBar();
        fileMenu = new javax.swing.JMenu();
        openMenuItem = new javax.swing.JMenuItem();
        saveMenuItem = new javax.swing.JMenuItem();
        saveAsMenuItem = new javax.swing.JMenuItem();
        exitMenuItem = new javax.swing.JMenuItem();
        editMenu = new javax.swing.JMenu();
        cutMenuItem = new javax.swing.JMenuItem();
        copyMenuItem = new javax.swing.JMenuItem();
        pasteMenuItem = new javax.swing.JMenuItem();
        deleteMenuItem = new javax.swing.JMenuItem();
        helpMenu = new javax.swing.JMenu();
        contentsMenuItem = new javax.swing.JMenuItem();
        aboutMenuItem = new javax.swing.JMenuItem();

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane3.setViewportView(jTextArea1);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setPreferredSize(new java.awt.Dimension(1000, 700));

        jToolBar1.setRollover(true);

        btnGetMail.setText("Get Email");
        btnGetMail.setFocusable(false);
        btnGetMail.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnGetMail.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnGetMail.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGetMailActionPerformed(evt);
            }
        });
        jToolBar1.add(btnGetMail);

        jButton2.setText("Send Email");
        jButton2.setFocusable(false);
        jButton2.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton2.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        jToolBar1.add(jButton2);
        jToolBar1.add(jSeparator1);

        jButton3.setText("Manage Account");
        jButton3.setFocusable(false);
        jButton3.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton3.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });
        jToolBar1.add(jButton3);

        btn_ManageKey.setText("Manage Key");
        btn_ManageKey.setFocusable(false);
        btn_ManageKey.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btn_ManageKey.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btn_ManageKey.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_ManageKeyActionPerformed(evt);
            }
        });
        jToolBar1.add(btn_ManageKey);

        jtaNoiDungEmail.setColumns(20);
        jtaNoiDungEmail.setRows(5);
        jScrollPane4.setViewportView(jtaNoiDungEmail);

        jtDanhSachEmail.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        jtDanhSachEmail.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jtDanhSachEmailMouseClicked(evt);
            }
        });
        jScrollPane5.setViewportView(jtDanhSachEmail);

        jbtnMoreInfo.setText("More Infomation");

        jbtnDeleteMail.setText("Delete Mail");
        jbtnDeleteMail.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnDeleteMailActionPerformed(evt);
            }
        });

        btnDownloadAtt.setText("Download Attachment");
        btnDownloadAtt.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDownloadAttActionPerformed(evt);
            }
        });

        fileMenu.setMnemonic('f');
        fileMenu.setText("File");

        openMenuItem.setMnemonic('o');
        openMenuItem.setText("Open");
        fileMenu.add(openMenuItem);

        saveMenuItem.setMnemonic('s');
        saveMenuItem.setText("Save");
        fileMenu.add(saveMenuItem);

        saveAsMenuItem.setMnemonic('a');
        saveAsMenuItem.setText("Save As ...");
        saveAsMenuItem.setDisplayedMnemonicIndex(5);
        fileMenu.add(saveAsMenuItem);

        exitMenuItem.setMnemonic('x');
        exitMenuItem.setText("Exit");
        exitMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        editMenu.setMnemonic('e');
        editMenu.setText("Edit");

        cutMenuItem.setMnemonic('t');
        cutMenuItem.setText("Cut");
        editMenu.add(cutMenuItem);

        copyMenuItem.setMnemonic('y');
        copyMenuItem.setText("Copy");
        editMenu.add(copyMenuItem);

        pasteMenuItem.setMnemonic('p');
        pasteMenuItem.setText("Paste");
        editMenu.add(pasteMenuItem);

        deleteMenuItem.setMnemonic('d');
        deleteMenuItem.setText("Delete");
        editMenu.add(deleteMenuItem);

        menuBar.add(editMenu);

        helpMenu.setMnemonic('h');
        helpMenu.setText("Help");

        contentsMenuItem.setMnemonic('c');
        contentsMenuItem.setText("Contents");
        helpMenu.add(contentsMenuItem);

        aboutMenuItem.setMnemonic('a');
        aboutMenuItem.setText("About");
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        setJMenuBar(menuBar);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(265, 265, 265)
                        .addComponent(jbtnMoreInfo)
                        .addGap(18, 18, 18)
                        .addComponent(jbtnDeleteMail)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 342, Short.MAX_VALUE)
                        .addComponent(btnDownloadAtt))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jScrollPane4)
                            .addComponent(jScrollPane5, javax.swing.GroupLayout.DEFAULT_SIZE, 976, Short.MAX_VALUE))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane5, javax.swing.GroupLayout.PREFERRED_SIZE, 161, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jbtnMoreInfo)
                    .addComponent(jbtnDeleteMail)
                    .addComponent(btnDownloadAtt))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane4, javax.swing.GroupLayout.DEFAULT_SIZE, 465, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitMenuItemActionPerformed
        System.exit(0);
    }//GEN-LAST:event_exitMenuItemActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        // TODO add your handling code here:
        AddAccount frm = new AddAccount();
        frm.show();
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        SendMail frm = new SendMail();
        frm.show();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void btnGetMailActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGetMailActionPerformed
        // TODO add your handling code here:
        LayMailTuServer();
    }//GEN-LAST:event_btnGetMailActionPerformed

    private Message[] NhanMail(final ThongTinTaiKhoanMail mail) {
        Properties props = new Properties();

        try {
            props.put("mail.smtp.host", mail.getPop());
            props.put("mail.smtp.port", mail.getPopport());
            props.put("mail.smtp.starttls.enable", "true");
            javax.mail.Authenticator pa = new javax.mail.Authenticator() {

                public PasswordAuthentication getpassPasswordAuthentication() {
                    return new PasswordAuthentication(mail.getEmail(), mail.getPassword());
                }
            };
            Session ss = Session.getDefaultInstance(props, pa);
            store = ss.getStore("pop3s");
            store.connect(mail.getPop(), mail.getEmail(), mail.getPassword());
            inbox = store.getFolder("INBOX");
            Message[] messages = null;
            if (inbox != null) {
                inbox.open(Folder.READ_WRITE);
                messages = inbox.getMessages();
            }
            //close inbox nhung khong xoa messages[] - nhung chay chua duoc.
            //inbox.close(true);
            //store.close();

            return messages;


        } catch (Exception ex) {
        }



        return null;
    }

    private void LayMailTuServer() {
        mail = ThongTinTaiKhoanMailDAO.layThongTinTaiKhoanMail();
        messages = NhanMail(mail);

        try {
            for (int i = this.tableModel.getRowCount(); i > 0; i--) {
                this.tableModel.removeRow(i - 1);
            }
            for (int i = 0; i < messages.length; i++) {
                Vector vt = new Vector();
                InternetAddress intAdd = (InternetAddress) messages[i].getFrom()[0];
                vt.add(intAdd.getPersonal());
                vt.add(messages[i].getSubject());
                SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
                String dateRec = sdf.format(messages[i].getSentDate());
                vt.add(dateRec);
                String size = Integer.toString((messages[i].getSize() / 1024) + 1) + " KB";
                vt.add(size);
                this.tableModel.addRow(vt);
            }
        } catch (Exception ex) {
        }
    }
    private Hashtable<String, ThongTinKey> myKey = new Hashtable<>();
    private Hashtable<String, ThongTinKey> friendKey = new Hashtable<>();
    private void jtDanhSachEmailMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jtDanhSachEmailMouseClicked
        // TODO add your handling code here:
        try {
            this.btnDownloadAtt.setVisible(false);
            int dong = this.jtDanhSachEmail.getSelectedRow();
            String str = "";



            Multipart multipart = (Multipart) messages[dong].getContent();
            int loopGetPart = 0;
            InternetAddress intAdd = (InternetAddress) messages[dong].getFrom()[0];
            ArrayList<ThongTinKey> arrKey = ThongTinKeyDAO.layTatCaThongTinKey();

            for (int j = 0; j < arrKey.size(); j++) {
                if (arrKey.get(j).getDiaChiMail().equals(intAdd.getAddress().toString())) {
                    friendKey.put(arrKey.get(j).getLoaiKey(), arrKey.get(j));
                }
                if (arrKey.get(j).getDiaChiMail().equals(ThongTinTaiKhoanMailDAO.layThongTinTaiKhoanMail().getEmail() + "@gmail.com")) {
                    myKey.put(arrKey.get(j).getLoaiKey(), arrKey.get(j));
                }
            }

            if (multipart.getCount() <= 2) {

                for (int h = 0; h < multipart.getCount(); h++) {
                    BodyPart bodyPart1 = multipart.getBodyPart(h);
                    String disposition1 = bodyPart1.getDisposition();
                    if (disposition1 != null && (disposition1.equals(BodyPart.ATTACHMENT))) {
                        this.btnDownloadAtt.setVisible(true);
                        this.btnDownloadAtt.setText("Download All Attachment File");
                    } else {

                        if (bodyPart1.getContent() instanceof Multipart) {
                            Multipart mp = (Multipart) bodyPart1.getContent();
                            for (int j = 0; j < mp.getCount(); j++) {
                                BodyPart bp = mp.getBodyPart(j);
                                str = str + bp.getContent();
                            }
                        } else {
                            str = str + bodyPart1.getContent();
                        }
                    }
                }
                  jbtnDeleteMail.setVisible(true);
            jtaNoiDungEmail.setText(str);
                return;
            }
            String type = multipart.getBodyPart(multipart.getCount() - 1).getContent().toString();
            if (Integer.parseInt(type.substring(1)) == 3 || Integer.parseInt(type.substring(1)) == 4) {

                loopGetPart = multipart.getCount() - 2;
//                if(EmailTools.VerifySignature(friendKey.get("Public").getDuongDan(), multipart.getBodyPart(multipart.getCount()-2).getContent().toString().getBytes(), multipart.getBodyPart(0).getContent().toString())){
//                    
//                }
            } else {
                loopGetPart = multipart.getCount() - 1;
            }


            for (int i = 0; i < loopGetPart; i++) {
                BodyPart bodyPart = multipart.getBodyPart(i);
                String disposition = bodyPart.getDisposition();
                if (disposition != null && (disposition.equals(BodyPart.ATTACHMENT))) {
                    this.btnDownloadAtt.setVisible(true);
                    this.btnDownloadAtt.setText("Download All Attachment File");
                } else {

                    if (bodyPart.getContent() instanceof Multipart) {
                        Multipart mp = (Multipart) bodyPart.getContent();
                        for (int j = 0; j < mp.getCount(); j++) {
                            BodyPart bp = mp.getBodyPart(j);
                            str = str + bp.getContent();
                        }
                    } else {
                        if (Integer.parseInt(multipart.getBodyPart(multipart.getCount() - 1).getContent().toString().substring(0, 1)) == 2) {
                            if(myKey.get("Private") != null){
                            str = str + EmailTools.DecrypByKey(myKey.get("Private").getDuongDan(), bodyPart.getContent().toString(), 1);
                            byte[] test = new sun.misc.BASE64Decoder().decodeBuffer(str);

                            str = EmailTools.DecryptByPreSharedKey(test, myKey.get("PreShared").getDuongDan());

                            continue;
                            }
                            else{
                               JFrame fr1 = new JFrame("Show Message Dialog");
                                JOptionPane.showMessageDialog(fr1, "Ban Phai Them Private Key Cua Ban Vao"); 
                               str = str + bodyPart.getContent(); 
                            }
                        }
                        if (Integer.parseInt(multipart.getBodyPart(multipart.getCount() - 1).getContent().toString().substring(0, 1)) == 1) {
                            if(myKey.get("PreShared") != null){
                            byte[] test = new sun.misc.BASE64Decoder().decodeBuffer(bodyPart.getContent().toString());
                            str = str + EmailTools.DecryptByPreSharedKey(test, myKey.get("PreShared").getDuongDan());
                            continue;
                            }
                            else{
                                JFrame fr1 = new JFrame("Show Message Dialog");
                                JOptionPane.showMessageDialog(fr1, "Ban Phai Them Shared Key Cua Ban Vao"); 
                               str = str + bodyPart.getContent(); 
                            }
                        }

                        str = str + bodyPart.getContent();


                    }
                }
            }
            jbtnDeleteMail.setVisible(true);
            jtaNoiDungEmail.setText(str);
            byte[] test1 = new sun.misc.BASE64Decoder().decodeBuffer(multipart.getBodyPart(multipart.getCount() - 2).getContent().toString());
            String oringalContent = multipart.getBodyPart(0).getContent().toString();
            if(friendKey.get("Public")!=null){
            if (!EmailTools.VerifySignature(friendKey.get("Public").getDuongDan(), test1, oringalContent)) {
                JFrame fr = new JFrame("Show Message Dialog");
                JOptionPane.showMessageDialog(fr, "Ban Phai Can Than Co The Day La Mail Gia Mao");
            }
            }
            else{
                JFrame fr = new JFrame("Show Message Dialog");
                JOptionPane.showMessageDialog(fr, "Ban Nen Them Public Key Cua Nguoi Gui Mail Cho Ban De Chung Thuc Chu Ky Dien Tu"); 
            }

        } catch (Exception ex) {
        }

    }//GEN-LAST:event_jtDanhSachEmailMouseClicked

    private void btnDownloadAttActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDownloadAttActionPerformed
        // TODO add your handling code here:
        try {
            int dong = this.jtDanhSachEmail.getSelectedRow();
            Multipart multipart = (Multipart) messages[dong].getContent();
            final JFileChooser fc = new JFileChooser();
            fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            int returnVal = fc.showOpenDialog(this);
            String path = fc.getSelectedFile().getAbsolutePath();
            for (int x = 0; x < multipart.getCount(); x++) {
                BodyPart bodyPart = multipart.getBodyPart(x);
                String disposition = bodyPart.getDisposition();
                if (disposition != null && (disposition.equals(BodyPart.ATTACHMENT))) {
                    InputStream instream = bodyPart.getInputStream();

                    OutputStream out = new FileOutputStream(new File(path + "\\" + bodyPart.getFileName()));
                    int read = 0;
                    byte[] bytes = new byte[1024];
                    while ((read = instream.read(bytes)) != -1) {
                        out.write(bytes, 0, read);
                    }

                    instream.close();
                    out.flush();
                    out.close();


                    File fileTemp = new File(path + "\\" + bodyPart.getFileName());

                    FileInputStream fis = new FileInputStream(fileTemp.getPath());
                    byte[] arrData = new byte[(int) fileTemp.length()];
                    fis.read(arrData);
                    fis.close();
                    byte[] arrSource = null;
                    if (Integer.parseInt(multipart.getBodyPart(multipart.getCount() - 1).getContent().toString().substring(0, 1)) == 2) {

                        String temp = fileTemp.getPath().replace("_Enscrypt", "");
                        temp = temp.replace("_EnsPre", "");

                        Cipher cipher = Cipher.getInstance("RSA");
                        EmailTools.EncryptOrDecryptFile(fileTemp.getPath(), temp, myKey.get("Private").getDuongDan(), cipher.DECRYPT_MODE);



                        File fileTempAsym = new File(temp);
                        FileInputStream fisAsym = new FileInputStream(temp);
                        byte[] arrDataAsym = new byte[(int) fileTempAsym.length()];
                        fisAsym.read(arrDataAsym);
                        fisAsym.close();
                        arrSource = EmailTools.DecryptByPreSharedKeyForFile(arrDataAsym, myKey.get("PreShared").getDuongDan());


                    }
                    if (Integer.parseInt(multipart.getBodyPart(multipart.getCount() - 1).getContent().toString().substring(0, 1)) == 1) {
                        arrSource = EmailTools.DecryptByPreSharedKeyForFile(arrData, myKey.get("PreShared").getDuongDan());

                    }

                    String temp = bodyPart.getFileName().replace("_Enscrypt", "");
                    temp = temp.replace("_EnsPre", "");
                    OutputStream outputWriter = new FileOutputStream(new File(path + "\\" + temp));
                    outputWriter.write(arrSource);
                    outputWriter.close();

//                    OutputStream out = new FileOutputStream(new File(path + "\\" + temp));
//                    int read = 0;
//                    byte[] bytes = new byte[1024];
//                    while ((read = instream.read(bytes)) != -1) {
//                        out.write(bytes, 0, read);
//                    }
//                    
//                    instream.close();
//                    out.flush();
//                    out.close();


                }
            }
        } catch (Exception ex) {
            try {
                throw ex;
            } catch (Exception ex1) {
                Logger.getLogger(MailManagement.class.getName()).log(Level.SEVERE, null, ex1);
            }
        }




    }//GEN-LAST:event_btnDownloadAttActionPerformed

    private void jbtnDeleteMailActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnDeleteMailActionPerformed
        // TODO add your handling code here:
        try {

            JFrame frame = new JFrame("Show Message Dialog");
            int flag = JOptionPane.showConfirmDialog(frame, "Bạn có chắc là muốn xóa email này ?");
            if (flag == 0) {
                int dong = this.jtDanhSachEmail.getSelectedRow();
                //Chi xoa mail o client ---> CheDoXoaMail == 1
                if (mail.getCheDoXoaMail() == 1) {
                    messages[dong].setFlag(Flags.Flag.DELETED, true);
                    inbox.close(true);
                    store.close();
                }
                //Chi xoa mail tren server ---> Che DoXoaMail == 2
                if (mail.getCheDoXoaMail() == 2) {
                }
                //Xoa mail o ca client va server --> CheDoXoaMail == 3
                if (mail.getCheDoXoaMail() == 3) {
//                    //messages[dong].
//                    messages[dong].setFlag(Flags.Flag.DELETED, true);
//                    Folder fo = messages[dong].getFolder();
//                    fo.close(true);
//                    fo.open(Folder.READ_WRITE);
//                    //inbox.close(false);
//                    //store.close();
                }
                LayMailTuServer();
            } else {
                //JOptionPane.showMessageDialog(frame, "Thông tin KHÔNG được lưu !");
            }
        } catch (Exception ex) {
        }
    }//GEN-LAST:event_jbtnDeleteMailActionPerformed

    private void btn_ManageKeyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_ManageKeyActionPerformed
        // TODO add your handling code here:
        ManageKey frm = new ManageKey();
        frm.show();
    }//GEN-LAST:event_btn_ManageKeyActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MailManagement.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MailManagement.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MailManagement.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MailManagement.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new MailManagement().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem aboutMenuItem;
    private javax.swing.JButton btnDownloadAtt;
    private javax.swing.JButton btnGetMail;
    private javax.swing.JButton btn_ManageKey;
    private javax.swing.JMenuItem contentsMenuItem;
    private javax.swing.JMenuItem copyMenuItem;
    private javax.swing.JMenuItem cutMenuItem;
    private javax.swing.JMenuItem deleteMenuItem;
    private javax.swing.JMenu editMenu;
    private javax.swing.JMenuItem exitMenuItem;
    private javax.swing.JMenu fileMenu;
    private javax.swing.JMenu helpMenu;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JScrollPane jScrollPane5;
    private javax.swing.JToolBar.Separator jSeparator1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JButton jbtnDeleteMail;
    private javax.swing.JButton jbtnMoreInfo;
    private javax.swing.JTable jtDanhSachEmail;
    private javax.swing.JTextArea jtaNoiDungEmail;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JMenuItem openMenuItem;
    private javax.swing.JMenuItem pasteMenuItem;
    private javax.swing.JMenuItem saveAsMenuItem;
    private javax.swing.JMenuItem saveMenuItem;
    // End of variables declaration//GEN-END:variables
}
